package com.study.threadpool.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author huang
 */
@Configuration
@EnableAsync
public class ThreadPoolConf implements AsyncConfigurer {
    @Override
    public Executor getAsyncExecutor() {
        // 定义线程池
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数
        executor.setCorePoolSize(10);
        // 最大线程数
        executor.setMaxPoolSize(100);
        // 队列容量
        executor.setQueueCapacity(1000);
        // 拒绝策略, 直接拒绝不抛出异常
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
        // 线程空闲存活时间(大于核心线程数的线程)
        executor.setKeepAliveSeconds(60);
        // 关闭线程时, 等待正在执行的任务执行完毕
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }
}
